﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Xml.Serialization;
using System.Xml;
namespace WinnerCMS.Silverlight
{
    public class SerializableHelper
    {
        public static T JsonDeSerialize<T>(string jsonString)
        {
            if (string.IsNullOrEmpty(jsonString)) return default(T);

            try
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));

                MemoryStream mStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));

                return (T)serializer.ReadObject(mStream);
            }
            catch
            {
                return default(T);
            }
        }
        public static string SerializeToJson<T>(T t)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(t.GetType());
            MemoryStream stream = new MemoryStream();
            serializer.WriteObject(stream, t);
            byte[] dataBytes = new byte[stream.Length];
            stream.Position = 0;
            stream.Read(dataBytes, 0, (int)stream.Length);
            return Encoding.UTF8.GetString(dataBytes, 0, dataBytes.Length);
        }
    }
}